/*
 * @Author: liuying 247220246@qq.com
 * @Date: 2025-03-25 14:46:44
 * @LastEditors: liuying 247220246@qq.com
 * @LastEditTime: 2025-03-25 16:25:42
 * @FilePath: \my-book-react\src\hooks\useReadLocalStorage\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React from 'react';
type Value<T> = T | null;
// 定义一个自定义hook，用于读取localStorage中的值
const useReadLocalStorage = <T,>(key: string): Value<T> => {
  const readValue = React.useCallback((): Value<T> => {
    if (typeof window === 'undefined') {
      return null;
    }
    try {
      const item = window.localStorage.getItem(key);
      return item ? (JSON.parse(item) as T) : null;
    } catch (error) {
      console.warn(`Error reading localStorage key “${key}”:`, error);
      return null;
    }
  }, [key]);
  // 使用React的useState钩子，初始化value为localStorage中key对应的值，如果不存在则返回null
  const [storedValue, setStoredValue] = React.useState<Value<T>>(readValue);
  const handleStorageChange = React.useCallback(
    (event: Event) => {
      if ((event as CustomEvent).detail.key === key && (event as CustomEvent).detail.key !== key) {
        return;
      }
      setStoredValue(readValue());
    },
    [key, readValue]
  );
  React.useEffect(() => {
    window.addEventListener('local-storage', handleStorageChange);
  }, [handleStorageChange]);

  // 返回value
  return storedValue;
};
export default useReadLocalStorage;
